﻿using System.Linq;
using AutoMapper;
using Fee;
using Fee.ViewModel;
using Identity.Searcher;
using JwtWebApi.Data;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;

namespace JwtWebApi.Controllers.Manage
{
    [Authorize]
    [Route("manage/[controller]")]
    [ApiController]
    [EnableCors]
    public class ProjectController : Controller
    {
        private readonly ApplicationDbContext _context;

        public ProjectController(ApplicationDbContext context)
        {
            _context = context;
        }

        [HttpGet("list")]
        public IActionResult Index([FromQuery] ProjectSearch search)
        {
            var query = _context.Projects.Where(project =>
                string.IsNullOrEmpty(search.Name) || project.Name.Contains(search.Name)
            );
            return Json(
                new
                {
                    data = query.Skip(search.GetSkip()).Take(search.PageSize ?? 30)
                        .Select(f => Mapper.Map<ProjectDetailViewModel>(f)),
                    total = query.Count()
                });
        }

        [HttpPost("save")]
        public IActionResult Save([FromBody] ProjectDetailViewModel model)
        {
            var proj = Mapper.Map<Project>(model);
            if (model.Id == 0)
                _context.Add(proj);
            else
                _context.Update(proj);
            _context.SaveChanges();
            return Json(new
            {
                message = "成功",
                projectId = proj.Id,
                successed = true
            });
        }

        [HttpPost("delete/{id}")]
        public IActionResult Delete(int id)
        {
            var project = _context.Projects.FirstOrDefault(f => f.Id == id);
            if (project != null)
                _context.Remove(project);
            _context.SaveChanges();
            return Json(new {successed = true, message = "删除成功"});
        }

        [HttpGet("get/{id}")]
        public IActionResult Get(int id)
        {
            var district = _context.Projects
                .FirstOrDefault(_ => _.Id == id);
            return Json(district);
        }
    }
}